package com.infinit.easyreader.utils;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.infinit.easyreader.ui.MainActivity;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 类： [V 1.0.0]
 * 包含类 : com.infinit.easyreader.utils
 * 作用：处理程序异常崩溃的问题
 * Created by rzy on 2016/1/29.
 */


public class ErrorHandler implements Thread.UncaughtExceptionHandler {
    private static final int CODE_RESTART = 100;
    private Context context;

    public ErrorHandler(Context context) {
        this.context = context;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        //捕捉异常并且保存在文件中
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        ex.printStackTrace(printWriter);
        final String errorMsg = printWriter.toString();
        Log.d("TAG", "uncaughtException: " + errorMsg);
        //打开一个日志记录文件
        try {
            FileOutputStream fos = context.openFileOutput("error.txt", Context.MODE_PRIVATE);
            printWriter = new PrintWriter(fos);
            printWriter.print(errorMsg);
            printWriter.flush();
            printWriter.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        //提示错误信息
        new Thread() {
            @Override
            public void run() {

                Looper.prepare();
                Toast.makeText(context, "糟糕，程序崩溃了，正在为您重新启动！请稍后", Toast.LENGTH_SHORT).show();
                Looper.loop();
            }
        }.start();

        //重新启动该应用
        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, CODE_RESTART, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        //定时器
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, 3000, pendingIntent);
    }
}



